# run_training.py
"""
模型训练启动脚本
放在项目根目录：D:\Py\code\DjangoProject\ExamPulse\run_training.py
"""

import os
import sys
import django
import logging

# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


def setup_environment():
    """设置Django环境"""
    try:
        # 添加当前目录到Python路径
        project_root = os.path.dirname(os.path.abspath(__file__))
        sys.path.insert(0, project_root)

        # 设置Django环境
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ExamPulse.settings')

        # 初始化Django
        django.setup()
        logger.info("✅ Django环境设置成功")

        return True

    except Exception as e:
        logger.error(f"❌ 环境设置失败: {e}")
        return False


def main():
    """主函数"""
    print("=" * 50)
    print("🚀 开始模型训练流程")
    print("=" * 50)

    # 1. 设置环境
    if not setup_environment():
        return

    # 2. 导入训练器
    try:
        from prediction.ml.trainers.model_trainer import ModelTrainer
        logger.info("✅ 模型训练器导入成功")
    except ImportError as e:
        logger.error(f"❌ 导入失败: {e}")
        logger.info("请检查：")
        logger.info("1. 是否在项目根目录运行")
        logger.info("2. prediction.ml 目录结构是否正确")
        logger.info("3. 所有 __init__.py 文件是否存在")
        return

    # 3. 创建训练器并训练
    try:
        trainer = ModelTrainer()
        logger.info("✅ 训练器实例化成功")

        # 显示模型信息
        model_info = trainer.get_model_info()
        logger.info(f"📊 模型状态: {model_info}")

        # 开始训练
        logger.info("🎯 开始训练模型...")
        result = trainer.train()

        # 显示训练结果
        print("\n" + "=" * 50)
        print("🏆 训练结果")
        print("=" * 50)

        if result.get('success'):
            logger.info(f"✅ 训练成功!")
            logger.info(f"   训练集 R²: {result.get('train_score', 0):.4f}")
            logger.info(f"   测试集 R²: {result.get('test_score', 0):.4f}")
            logger.info(f"   平均绝对误差: {result.get('mae', 0):.2f} 分")
            logger.info(f"   训练样本数: {result.get('training_samples', 0)}")
            logger.info(f"   特征数量: {result.get('feature_count', 0)}")

            # 显示最重要的特征
            feature_importance = result.get('feature_importance', {})
            if feature_importance:
                top_features = sorted(feature_importance.items(), key=lambda x: x[1], reverse=True)[:5]
                logger.info("📈 最重要的5个特征:")
                for feature, importance in top_features:
                    logger.info(f"   {feature}: {importance:.3f}")

        else:
            logger.error(f"❌ 训练失败: {result.get('error', '未知错误')}")

    except Exception as e:
        logger.error(f"❌ 训练过程出错: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()